/*
 * Copyright  2008 Sun Microsystems, Inc. All rights reserved.
 * Use is subject to license terms.
 *
 */
package com.sun.lwuit.uidemo;

import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import com.sun.dtv.lwuit.Button;
import com.sun.dtv.lwuit.Command;
import com.sun.dtv.lwuit.Component;
import com.sun.dtv.lwuit.Container;
import com.sun.dtv.lwuit.Form;
import com.sun.dtv.lwuit.Image;
import com.sun.dtv.lwuit.Label;
import com.sun.dtv.lwuit.TextArea;
import com.sun.dtv.lwuit.animations.CommonTransitions;
import com.sun.dtv.lwuit.animations.Transition;
import com.sun.dtv.lwuit.events.ActionEvent;
import com.sun.dtv.lwuit.events.ActionListener;
import com.sun.dtv.lwuit.events.FocusListener;
import com.sun.dtv.lwuit.layouts.BorderLayout;
import com.sun.dtv.lwuit.layouts.GridLayout;
import com.sun.dtv.lwuit.plaf.DefaultLookAndFeel;
import com.sun.dtv.lwuit.plaf.Style;
import com.sun.dtv.lwuit.plaf.UIManager;
import com.sun.dtv.lwuit.util.Resources;
import com.sun.dtv.ui.DTVContainer;

/**
 * Bootstraps the UI toolkit demos
 * 
 * @author Shai Almog
 */
public class UIDemo implements ActionListener {

	private static final int EXIT_COMMAND = 1;
	private static final int RUN_COMMAND = 2;
	private static final int BACK_COMMAND = 3;
	private static final int ABOUT_COMMAND = 4;
	private static final Command runCommand = new Command("Run", RUN_COMMAND);
	private static final Command exitCommand = new Command("Exit", EXIT_COMMAND);
	private static final Command backCommand = new Command("Back", BACK_COMMAND);
	private static final Command aboutCommand = new Command("About", ABOUT_COMMAND);
	private static final Demo[] DEMOS = new Demo[] { new ThemeDemo(), new RenderingDemo(), new AnimationDemo(),
			new ButtonsDemo(),
			/* new TransitionDemo(), */new FontDemo(), new TabbedPaneDemo(), new DialogDemo(), new LayoutDemo(),
			new CarouselDemo() };
	private Demo currentDemo;
	private static Transition componentTransitions;
	private Hashtable demosHash = new Hashtable();
	private static Form mainMenu;
	private Container mainCont;
	// private int cols;
	private int elementWidth;

	public UIDemo() {
		try {
			// for removing the error dialogs
			// ImplementationFactory.setInstance(new
			// NoErrImplementaionFactory());

			// Display.init(new Context(0,0,1920,1080,55,57));
			// Display.init(new Context(0,0,720,580,55,57));
			UIManager.getInstance().getLookAndFeel().setDefaultMenuTransitionIn(CommonTransitions.createEmpty());
			UIManager.getInstance().getLookAndFeel().setDefaultMenuTransitionOut(CommonTransitions.createEmpty());

			((DefaultLookAndFeel) UIManager.getInstance().getLookAndFeel()).setCheckBoxImages(Image
					.createImage("/check-sel.png"), Image.createImage("/check-unsel.png"));
			((DefaultLookAndFeel) UIManager.getInstance().getLookAndFeel()).setRadioButtonImages(Image
					.createImage("/radio-sel.png"), Image.createImage("/radio-unsel.png"));

			InputStream stream = getClass().getResourceAsStream("/resources.res");
			Resources r2 = Resources.open(stream);
			stream.close();

			// resources are built during the build process
			// open the build.xml file to figure out how to construct the
			// resource files
			Resources r1 = Resources.open("/javaTheme.res");
			UIManager.getInstance().setThemeProps(r1.getTheme(r1.getThemeResourceNames()[0]));

			setMainForm(r2);

		} catch (Throwable ex) {
			ex.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new UIDemo();

	}

	// private static class NoErrImplementaionFactory extends
	// ImplementationFactory {
	// public LWUITImplementation createImplementaion() {
	// return new NoErrAWTImplementation();
	// }
	// }
	// private static class NoErrAWTImplementation extends AWTImplementation {
	// public boolean handleEDTException (Throwable err) {
	// return true;
	// }
	// }

	// /**
	// * Used instead of using the Resources API to allow us to fetch locally
	// downloaded
	// * resources
	// *
	// * @param name the name of the resource
	// * @return a resources object
	// */
	public static Resources getResource(String name) throws IOException {
		return Resources.open("/" + name + ".res");
	}

	public static void setTransition(Transition in, Transition out) {
		// mainMenu.setTransitionInAnimator(in);
		// mainMenu.setTransitionOutAnimator(out);
	}

	public static void setMenuTransition(Transition in, Transition out) {
		// mainMenu.setMenuTransitions(in, out);
		// UIManager.getInstance().getLookAndFeel().setDefaultMenuTransitionIn(in);
		// UIManager.getInstance().getLookAndFeel().setDefaultMenuTransitionOut(out);
	}

	public static void setComponentTransition(Transition t) {
		componentTransitions = t;
		mainMenu.setSmoothScrolling(false);
	}

	public static Transition getComponentTransition() {
		return componentTransitions;
	}

	private void setMainForm(Resources r) {
		UIManager.getInstance().setResourceBundle(r.getL10N("localize", "en"));

		Style SoftButtonS = UIManager.getInstance().getComponentStyle("SoftButton");
		int screenW = DTVContainer.getCurrentDTVContainer().getWidth();
		int screenH = DTVContainer.getCurrentDTVContainer().getHeight();
		if (screenW > 960) {
			// System.out.println("(screenH*0.05) = "+(int)
			// (screenH*0.05)+", W = "+(screenW*0.05));
			SoftButtonS.setPadding((int) (screenH * 0.01), (int) (screenH * 0.05), (int) (screenW * 0.07),
					(int) (screenW * 0.07));
			UIManager.getInstance().setComponentStyle("SoftButton", SoftButtonS);

			Style titleS = UIManager.getInstance().getComponentStyle("Title");
			titleS.setPadding((int) (screenH * 0.05), (int) (screenH * 0.02), 3, 3);
			UIManager.getInstance().setComponentStyle("Title", titleS);
		}
		// application logic determins the number of columns based on the screen
		// size
		// this is why we need to be aware of screen size changes which is
		// currently
		// only received using this approach
		mainMenu = new MainScreenForm("LWUIT Demo") {
			protected void sizeChanged(int w, int h) {
				super.sizeChanged(w, h);
				try {
					setMainForm(Resources.open("/resources.res"));
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}

			public void keyPressed(int key) {
				super.keyPressed(key);
				System.out.println(">>>>>>> Key = " + key);
				if (key == 27 || key == 409 || key == 56) {
					System.exit(1);
				}
			}

		};
		mainMenu.setLayout(new BorderLayout());
		mainCont = new Container(new GridLayout(3, 4));

		mainCont.getStyle().setPadding(SoftButtonS.getPadding(Component.TOP), SoftButtonS.getPadding(Component.BOTTOM),
				SoftButtonS.getPadding(Component.LEFT), SoftButtonS.getPadding(Component.RIGHT));

		mainMenu.addComponent(BorderLayout.CENTER, mainCont);
		// mainMenu.setLayout(new GridLayout(3, 4));

		// int width = Display.getInstance().getDisplayWidth(); //get the
		// display width

		elementWidth = 0;

		// mainMenu.setTransitionOutAnimator(CommonTransitions.createFade(400));

		Image[] selectedImages = new Image[DEMOS.length];
		Image[] unselectedImages = new Image[DEMOS.length];

		final ButtonActionListener bAListner = new ButtonActionListener();
		for (int i = 0; i < DEMOS.length; i++) {
			Image temp = r.getImage(DEMOS[i].getName() + "_sel.png");
			selectedImages[i] = temp;
			unselectedImages[i] = r.getImage(DEMOS[i].getName() + "_unsel.png");
			final Button b = new Button(DEMOS[i].getName(), unselectedImages[i]);
			b.setRolloverIcon(selectedImages[i]);
			Style s = b.getStyle();
			s.setBorder(null);
			s.setBgTransparency(0);
			s.setBgSelectionColor(new Color(0xffffff));
			b.setAlignment(Label.HORIZONTAL_ALIGN_CENTER);
			b.setTextPosition(Label.BOTTOM);
			mainCont.addComponent(b);
			b.addActionListener(bAListner);
			b.addFocusListener(new FocusListener() {

				public void focusGained(Component cmp) {
					if (componentTransitions != null) {
						mainCont.replace(b, b, componentTransitions);
					}
				}

				public void focusLost(Component cmp) {
				}
			});

			demosHash.put(b, DEMOS[i]);
			elementWidth = Math.max(b.getPreferredSize().getWidth(), elementWidth);
		}

		// Calculate the number of columns for the GridLayout according to the
		// screen width
		// cols = width / elementWidth;
		// int rows = DEMOS.length / cols;
		// mainMenu.setLayout(new GridLayout(3, 4));

		// mainMenu.addComponent(BorderLayout.CENTER, mainContainer);

		mainMenu.addCommand(exitCommand);
		mainMenu.addCommand(aboutCommand);
		mainMenu.addCommand(runCommand);

		mainMenu.setCommandListener(this);
		// mainMenu.getStyle().setMargin(28,29,91,93);
		mainMenu.show();
	}

	/**
	 * Invoked when a command is clicked. We could derive from Command but that
	 * would require 3 separate classes.
	 */
	public void actionPerformed(ActionEvent evt) {
		Command cmd = evt.getCommand();
		switch (cmd.getId()) {
		case RUN_COMMAND:
			currentDemo = ((Demo) (demosHash.get(mainMenu.getFocused())));
			currentDemo.run(backCommand, this);
			break;
		case EXIT_COMMAND:
			System.exit(1);
			break;
		case BACK_COMMAND:
			currentDemo.cleanup();
			mainMenu.refreshTheme();
			mainMenu.show();

			// for series 40 devices
			System.gc();
			System.gc();
			break;
		case ABOUT_COMMAND:
			Form aboutForm = new Form("About");
			aboutForm.setScrollable(false);
			aboutForm.setLayout(new BorderLayout());
			TextArea aboutText = new TextArea(getAboutText(), 5, 10);
			aboutText.setEditable(false);
			aboutForm.addComponent(BorderLayout.CENTER, aboutText);
			aboutForm.addCommand(new Command("Back") {

				public void actionPerformed(ActionEvent evt) {
					mainMenu.show();
				}
			});
			aboutForm.show();
			break;
		}
	}

	private String getAboutText() {
		return "LWUIT Demo shows the main features for developing a User " + "Interface (UI) in Java ME. "
				+ "This demo contains inside additional different sub-demos "
				+ "to demonstrate key features, where each one can be reached "
				+ "from the main screen. For more details about each sub-demo, "
				+ "please visit the demo help screen. For more details, please "
				+ "contact us at lwuit-comments@sun.com.";
	}

	private class ButtonActionListener implements ActionListener {

		public void actionPerformed(ActionEvent evt) {
			currentDemo = ((Demo) (demosHash.get(evt.getSource())));
			currentDemo.run(backCommand, UIDemo.this);
		}
	}

}
